package com.ruoyi.site.controller;

import com.ruoyi.site.service.IStripeService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/site/stripe")
public class StripeWebhookController {

    private static final Logger log = LoggerFactory.getLogger(StripeWebhookController.class); // 初始化日志

    @Autowired
    private IStripeService stripeService;

    @PostMapping("/webhook")
    public ResponseEntity<String> handleStripeWebhook(
            HttpServletRequest request,
            @RequestHeader("Stripe-Signature") String stripeSignature) {

        log.info("【Stripe Webhook】收到回调请求，签名: {}", stripeSignature);

        byte[] payload;
        try {
            payload = IOUtils.toByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("读取原始请求体失败。", e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to read raw body.");
        }

        try {
            // 2. 调用 Service 处理事件，传递 byte[]
            stripeService.handleWebhook(payload, stripeSignature);

            log.info("【Stripe Webhook】事件处理成功.");
            return ResponseEntity.ok("Success");

        } catch (RuntimeException e) {
            log.error("【Stripe Webhook】处理失败，返回 400 Bad Request. Error: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Webhook Error: " + e.getMessage());

        } catch (Exception e) {
            log.error("【Stripe Webhook】系统未知错误.", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("System Error.");
        }
    }
}